package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Category;
import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchServlet extends HttpServlet {
    private static final String SEARCH_PRODUCT_FORM = "/WEB-INF/jsp/catalog/product.jsp";
    private static final String SEARCH_CATEGORY_FORM = "/WEB-INF/jsp/catalog/category.jsp";
    private static final String SEARCH_ITEM_FORM = "/WEB-INF/jsp/catalog/item.jsp";
    private String Id;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Id = req.getParameter("keyword");
        CatalogService catalogService = new CatalogService();
        Category category = catalogService.getCategory(Id);
        Product product = catalogService.getProduct(Id);
        Item item = catalogService.getItem(Id);
        if(category != null){
            List<Product> productList = catalogService.getProductListByCategory(Id);
            HttpSession session = req.getSession();
            session.setAttribute("category",category);
            session.setAttribute("productList",productList);
            req.getRequestDispatcher(SEARCH_CATEGORY_FORM).forward(req,resp);
        }else if(item != null){
            HttpSession session = req.getSession();
            session.setAttribute("product", item.getProduct());
            session.setAttribute("item", item);
            req.getRequestDispatcher(SEARCH_ITEM_FORM).forward(req, resp);
        }else if (product != null){
            List<Item> itemList = catalogService.getItemListByProduct(Id);
            HttpSession session = req.getSession();
            session.setAttribute("product",product);
            session.setAttribute("itemList",itemList);
            req.getRequestDispatcher(SEARCH_PRODUCT_FORM).forward(req,resp);
        }
    }


}
